package com.neuedu.springmvc.controller;

import com.neuedu.springmvc.ValidateV1;
import com.neuedu.springmvc.ValidateV2;
import com.neuedu.springmvc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * 项目：springmvc-java4
 * 创建时间：  2022-03-24   9:14
 * 作者 :jshand
 * 描述 :
 */
@Controller
@RequestMapping("valid")
public class ValidationController {


    /**
     * http://127.0.0.1:8080/springmvc/valid/v1?username=abcdefaa&password=123456789
     * @param user
     * @return
     */
    @RequestMapping(value ="v1")
    public String v1(
            @Validated(value = ValidateV1.class) User user, BindingResult bindingResult,
            String name,
            Model model
    ){

        //如果有错误消息， allErrors的长度大于0
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError allError : allErrors) {
            System.out.println("allError.getDefaultMessage() = " + allError.getDefaultMessage());
        }

        model.addAttribute("allErrors",allErrors);

        return "forward:/index.jsp";
    }




    //查询用户

    /**
     * http://127.0.0.1:8080/springmvc/valid/v1?name=aaaaaaa&address=harbinsss
     * @param user 查询条件 name、address
     * @param bindingResult
     * @param model
     * @return
     */
    @RequestMapping(value ="v2")
    public String v2(
            @Validated(value = ValidateV2.class) User user, BindingResult bindingResult , Model model
    ){

        System.out.println("user = " + user);
        //如果有错误消息， allErrors的长度大于0
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError allError : allErrors) {
            System.out.println("allError.getDefaultMessage() = " + allError.getDefaultMessage());
        }

        model.addAttribute("allErrors",allErrors);

        return "forward:/index.jsp";
    }

}
